using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace SqlTools.SchemaReader
{
	public class Index : DbObject
	{
		protected Table _table;
		protected short _indexID = -1;
		protected DbCollection<Column> _columns;



		public Index() : this("", 0, null) { }
		
		public Index(string name, int id, Table table)
			: base(name, id)
		{
			_columns = new DbCollection<Column>();
			_table = table;
		}

		public short IndexID
		{
			get { return _indexID; }
			internal set { _indexID = value; }
		}

		public DbCollection<Column> Columns
		{
			get { return _columns; }
		}

		public override DbObjectType Type
		{
			get { return DbObjectType.Index; }
		}

		public Table Table
		{
			get { return _table; }
			set { _table = value; }
		}

		public override void SaveXml(XmlDocument doc, XmlNode xmlParent)
		{
			XmlElement el = CreateXmlElement(doc, xmlParent);

			XmlElement xmlColumns = doc.CreateElement("Columns");
			el.AppendChild(xmlColumns);

			foreach ( Column column in _columns )
			{
				XmlElement xmlCol = doc.CreateElement("Column");
				xmlColumns.AppendChild(xmlCol);

				xmlCol.Attributes.Append(doc.CreateAttribute("columnid")).Value = column.ID.ToString();
			}
		}

		public override XmlElement CreateXmlElement(XmlDocument doc, XmlNode parent)
		{
			XmlElement el = base.CreateXmlElement(doc, parent);

			el.Attributes.Append(doc.CreateAttribute("indexid")).Value = _indexID.ToString();

			return el;
		}

		public override void LoadXml(XmlElement el, Database db)
		{
			base.LoadXml(el, db);

			string indexid = el.GetAttribute("indexid");
			if ( !short.TryParse(indexid, out _indexID) )
				_indexID = 0;

			XmlNodeList nodes = el.GetElementsByTagName("Columns");
			if ( nodes.Count > 0 )
			{
				XmlElement xmlColumns = nodes[0] as XmlElement;

				foreach ( XmlNode node in xmlColumns.ChildNodes )
				{
					if ( node.NodeType == XmlNodeType.Element )
					{
						XmlElement xmlCol = node as XmlElement;

						if ( xmlCol != null && xmlCol.Name == "Column" )
						{
							string columnid = xmlCol.GetAttribute("columnid");

							int colid = 0;

							if ( int.TryParse(columnid, out colid) )
							{
								Column column = _table.Columns.RetrieveByID(colid);
								this.Columns.Add(column);
							}
						}
					}
				}
			}
		}
	}
}
